#!/usr/bin/env python
# -*- encoding:utf8 -*-

""" 天文时钟 """

import ephem
import arrow
from flask import Flask, request, jsonify
from calc import get_sidereal_time, calc_hour_angle
from collections import OrderedDict

app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False


@app.route("/")
def index():
    return "太阳系天体时刻表"


@app.route("/hour-angle", methods={'POST'})
def polaris_hour():
    if request.method == 'GET':
        lat = request.args.get('lat')
        lon = request.args.get('lon')
        elev = request.args.get('elev')
    elif request.method == 'POST':
        lat = request.form['lat']
        lon = request.form['lon']
        elev = request.form['elev']

    data = {"polaris hour angle": calc_hour_angle(get_sidereal_time(lat, lon, elev))}

    return jsonify(data)


@app.route("/api", methods={'POST'})
def api():
    city = ephem.Observer()
    if request.method == 'GET':
        city.lat = request.args.get('lat')
        city.lon = request.args.get('lon')
        city.date = str(request.args.get('date'))
        city.elev = float(request.args.get('elev'))
    elif request.method == 'POST':
        city.lat = request.form['lat']
        city.lon = request.form['lon']
        city.date = str(request.form['date'])
        city.elev = float(request.form['elev'])

    sun = ephem.Sun()
    moon = ephem.Moon()
    venus = ephem.Venus()
    jupiter = ephem.Jupiter()
    mercury = ephem.Mercury()
    mars = ephem.Mars()
    saturn = ephem.Saturn()
    uranus = ephem.Uranus()
    neptune = ephem.Neptune()

    data = OrderedDict()
    data['sun'] = compute(city, sun)
    data['moon'] = compute(city, moon)
    data['venus'] = compute(city, venus)
    data['jupiter'] = compute(city, jupiter)
    data['mercury'] = compute(city, mercury)
    data['mars'] = compute(city, mars)
    data['saturn'] = compute(city, saturn)
    data['uranus'] = compute(city, uranus)
    data['neptune'] = compute(city, neptune)
    return jsonify(data)


def compute(city, target):
    time_zone = 'Asia/Shanghai'
    day = str(arrow.get(city.date.datetime()).format('YYYY-MM-DD'))
    # 计算当天rise时间
    previous_rising = str(arrow.get(city.previous_rising(target).datetime()).to(time_zone))
    if previous_rising.find(day) != -1:
        rising_time = previous_rising
    else:
        rising_time = str(arrow.get(city.next_rising(target).datetime()).to(time_zone))

    # 计算当天transit时间
    previous_transit = str(arrow.get(city.previous_transit(target).datetime()).to(time_zone))
    if previous_transit.find(day) != -1:
        transit_time = previous_transit
    else:
        transit_time = str(arrow.get(city.next_transit(target).datetime()).to(time_zone))
    # 计算当天下降时间
    previous_setting = str(arrow.get(city.previous_setting(target).datetime()).to(time_zone))
    if previous_setting.find(day) != -1:
        setting_time = previous_setting
    else:
        setting_time = str(arrow.get(city.next_setting(target).datetime()).to(time_zone))
    return {'rise': rising_time, 'transit': transit_time, 'sit': setting_time}


if __name__ == '__main__':
    app.run()
